import { Input, App } from 'antd'
import { useStreams } from '@/lib/utils'
import services from '@/services'

export function NotifyURL() {
  const { message } = App.useApp()
  const [isAdmin] = useStreams(services.auth.isAdmin$)
  const [webConfig] = useStreams(services.features.webConfig.data)
  const [notifyUrl, setNotifyUrl] = useState(webConfig.notifyUrl)

  const [saving, setSaving] = useState(false)
  async function save() {
    if (notifyUrl === webConfig.notifyUrl) return
    setSaving(true)
    const res = await services.features.webConfig.update({
      ...webConfig,
      notifyUrl: notifyUrl.trim(),
    })
    setSaving(false)
    if (res.success) void message.success('回调设置成功')
    else void message.warning(`回调设置失败：${res.error}`)
  }

  if (isAdmin !== true) return null

  return <div css={s.wrap}>
    <h5>API 回调</h5>
    <div css={s.tips}>
          <span>可通过此回调，接收沟通中台的事件，如：聊天消息、联系人变动... 详见：API 文档</span>
    </div>
    <Input
      value={notifyUrl}
      onChange={e => setNotifyUrl(e.target.value)}
      onBlur={save}
      placeholder="输入回调 URL，如：http://abc.com/api/callback"
      disabled={saving}
    />
  </div>
}

const s = {
  wrap: css`
    .ant-tabs-content-holder > .ant-tabs-content > .ant-tabs-tabpane & h5 {
      margin-bottom: 8px;
    }
  `,
  tips: css`
    color: #999;
    margin-bottom: 16px;
  `,
}
